﻿using MvcShopping.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace MvcShopping.Controllers
{
    public class AdminRegisterController : Controller
    {
        //
        // GET: /AdminRegister/
        MvcShoppingContext1 db = new MvcShoppingContext1();

        public ActionResult Index()
        {
            return View();
        }

            public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
        public ActionResult addMember() {
            return View();
        }
        ///添加管理员
        [HttpPost]
        public void addMember(string name, string password,
            string returnUrl)
        {
     
            String loginuser = name;
            String loginContent = "时间：" + DateTime.Now.ToLocalTime().ToString() + "ip:" + Request.UserHostAddress + " 添加管理员";
            Log log = new Log();
            log.operateName = loginuser;
            log.operateContent = loginContent;
            db.Logs.Add(log);
            db.SaveChanges();
            Admins admin = new Admins();
            admin.name = name;
            admin.password = password;
            db.Admins.Add(admin);
            db.SaveChanges();
        }


        /// <summary>
        /// 运行管理员登录
        [HttpPost]
        public ActionResult Login(string name, string password,
            string returnUrl)
        {
            if (ValidateAdmin(name, password))
            {
                if (string.IsNullOrEmpty(returnUrl))
                {
                    String loginuser = name;
                    String loginContent = "时间：" + DateTime.Now.ToLocalTime().ToString() + "ip:" + Request.UserHostAddress + " 登录后台";
                    Log log = new Log();
                    log.operateName = loginuser;
                    log.operateContent = loginContent;
                    db.Logs.Add(log);
                    db.SaveChanges(); 
                    return RedirectToAction("Add","Admin");
                }
                else
                {
                    return RedirectToAction(returnUrl);
                }
            }
            ModelState.AddModelError("", "你输入的帐号或密码错误");
            return View();
        }
        private bool ValidateAdmin(string name, string password)
        {
            
            var member = (from p in db.Admins
                          where p.name == name &&
                          p.password == password
                          select p).FirstOrDefault();
            return member != null;
        }

        //public ActionResult Logout()
        //{
        //    //清除窗体验证的cookie
        //    FormsAuthentication.SignOut();

        //    //清除所有曾经写入过的Session
        //    //Session.Clear();

        //    return RedirectToAction("Index", "Home");
        //}

    }
}
